package io.potato.ts.service;

import io.potato.core.AppException;
import io.potato.core.exception.NoDataAccessRightException;
import io.potato.core.exception.OperationHandlerException;
import io.potato.ts.domain.User;
import io.potato.ts.domain.UserGroupLink;
import io.potato.ts.repository.UserGroupLinkRepository;
import io.potato.ts.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.potato.core.CrudService;
import io.potato.ts.domain.UserGroup;
import io.potato.ts.repository.UserGroupRepository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;


/**
 * 用户组服务类
 * 
 * @author timl
 *
 * <p>2019-03-19 14:14:57</p>
 */
@Service
@Transactional
@Slf4j
public class UserGroupService extends CrudService<UserGroup, Integer> {

	@Autowired
	private UserGroupRepository repository;

	@Autowired
	private UserGroupLinkRepository linkRepository;

	@Autowired
	private UserRepository userRepository;

	@Override
	protected JpaRepository<UserGroup, Integer> getRepository() {
		return repository;
	}

	/**
	 * 查询的单位的用户组
	 * @param organId  单位ID
	 * @return  用户组列表
	 */
	public List<UserGroup> findByOrganId(Integer organId) {
		return repository.findByOrganId(organId);
	}

    /**
     * 查询用户组下的用户列表
     * @param userGroupId  用户组ID
     * @return  用户组列表
     */
    public List<User> findUser(Integer userGroupId, Integer organId) {
        return findUser(Arrays.asList(userGroupId), organId);
    }

    public List<User> findUser(List<Integer> userGroupIds, Integer organId) {
        if (userGroupIds == null || userGroupIds.isEmpty()) {
            return new ArrayList<>();
        }
        return userRepository.findByGroupId(userGroupIds, organId);
    }

    /**
     * 添加用户到用户组， 如果用户组原来已有这个用户， 会忽略
     * @param userGroupId  用户组ID
     * @param userIds  要添加的用户ID
     */
    public void saveUser(Integer userGroupId, List<Integer> userIds, Integer organId) {
        checkAndGetUserGroup(userGroupId, organId);

        List<UserGroupLink> list = new ArrayList<>();
        for (Integer userId : userIds) {
            Integer count = linkRepository.countByGroupIdAndUserId(userGroupId, userId);
            if (count < 1) {
                UserGroupLink link = new UserGroupLink();
                link.setGroupId(userGroupId);
                link.setUserId(userId);
                list.add(link);
            }
        }
        log.debug("" + list.size());
        if (list.size() > 0) {
            this.linkRepository.saveAll(list);
        }
    }

    /**
     * 保存用户组
     * @param userGroup  用户组
     * @param organId 单位ID
     */
    public void save(UserGroup userGroup, Integer organId) {
        if (userGroup == null) {
            userGroup.setOrganId(organId);
            super.save(userGroup);
        } else {
            Optional<UserGroup> optionalUserGroup = findById(userGroup.getId());
            if (optionalUserGroup.isPresent()) {
                UserGroup oldGroup = optionalUserGroup.get();
                if (!oldGroup.getOrganId().equals(organId)) {
                    // 只能修改自己单位的数据
                    throw new NoDataAccessRightException();
                }

                oldGroup.setGroupName(userGroup.getGroupName());
                super.save(oldGroup);
            } else {
                throw new AppException("记录不存在");
            }
        }
    }

    /**
     * 删除用户组下的用户
     * @param userGroupId 用户组ID
     * @param userIds 用户ID列表
     */
    public void deleteUser(Integer userGroupId, List<Integer> userIds, Integer organId) {
        checkAndGetUserGroup(userGroupId, organId);
        linkRepository.deleteByUserId(userGroupId, userIds);
    }

    /**
     * 删除用户组下所有用户
     * @param userGroupId 用户组ID
     */
    public void deleteUser(Integer userGroupId, Integer organId) {
        checkAndGetUserGroup(userGroupId, organId);
        linkRepository.deleteByGroupId(userGroupId);
    }

    /**
     * 删除用户组以及对应的用户
     * @param userGroupId 用户组ID
     * @param organId  单位ID
     */
    public void deleteGroup(Integer userGroupId, Integer organId) {

        checkAndGetUserGroup(userGroupId, organId);

        deleteById(userGroupId);

        linkRepository.deleteByGroupId(userGroupId);
    }

    private UserGroup checkAndGetUserGroup(Integer userGroupId, Integer organId) {
        Optional<UserGroup> optionalUserGroup = this.findById(userGroupId);
        if (!optionalUserGroup.isPresent()) {
            throw new AppException("用户组不存在");
        }

        if (!optionalUserGroup.get().getOrganId().equals(organId)) {
            throw new AppException("单位ID不匹配");
        }
        return optionalUserGroup.get();
    }
	
}
